<template>
    <div>
        <!--          面包屑-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item >🏠</el-breadcrumb-item>
            <el-breadcrumb-item>论坛管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!--        卡片区域-->
        <el-card class="box-card">

            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
<!--                <el-form-item label="帖子分类" prop="classificationName" >-->
<!--                    <el-input-->
<!--                            v-model="queryParams.topic.classificationName"-->
<!--                            placeholder="请输入帖子分类"-->
<!--                            clearable-->
<!--                            size="small"-->
<!--                            @keyup.enter.native="handleQuery"-->
<!--                    />-->
<!--                </el-form-item>-->
                <el-form-item label="帖子分类" prop="classificationName">
                    <el-select v-model="queryParams.topic.classificationName"  placeholder="请选择帖子分类">
                        <div v-for="item in classificationList" :key="item.id">
                            <el-option :label="item.className" :value="item.className"></el-option>
                        </div>
                    </el-select>
                </el-form-item>
                <el-form-item label="发布用户昵称" prop="userName">
                    <el-input
                            v-model="queryParams.topic.userName"
                            placeholder="请输入发布用户昵称"
                            clearable
                            size="small"
                            @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="发布时间" prop="issueTime">
                    <el-date-picker
                            v-model="issueTime"
                            end-placeholder="结束日期"
                            range-separator="至"
                            start-placeholder="开始日期"
                            type="datetimerange"
                            @change="handleIssueTime">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="帖子内容" prop="conent" >
                    <el-input
                            v-model="queryParams.topic.content"
                            placeholder="请输入发布内容"
                            clearable
                            size="small"
                            style="width: 500px"
                            @keyup.enter.native="handleQuery"
                    />
                </el-form-item>

<!--                <el-form-item label="排序方式">-->
<!--                    <el-select v-model="queryParams.topic.select" placeholder="请选择排序方式">-->
<!--                        <el-option label="按回复数量升序" value="shanghai"></el-option>-->
<!--                        <el-option label="按回复数量降序" value="beijing"></el-option>-->
<!--                    </el-select>-->
<!--                </el-form-item>-->

                <el-form-item  style='position: absolute;right:10px;'>
                    <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetForm('queryForm')">重置</el-button>
                </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                            type="success"
                            icon="el-icon-edit"
                            size="mini"
                            :disabled="single"
                            @click="handleUpdate"
                    >修改</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            :disabled="multiple"
                            @click="handleDelete"
                    >删除</el-button>
                </el-col>

                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>


            <el-table v-loading="loading" :data="topicList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="发布用户昵称" align="center" prop="userName" />
                <el-table-column label="帖子分类" align="center" prop="classificationName" />
                <el-table-column label="发布时间" align="center" prop="time" />
                <el-table-column label="帖子内容" align="center" width="700px" prop="content">
                    <template slot-scope="{ row }">
                        <el-button :plain="true" @click="openHTML(row.content)" style="height: 80px" type="text" >
                            <div
                                    id="content"
                                    v-html="row.content"
                                    style="
                                         overflow: hidden;
                                         text-overflow: ellipsis;
                                         white-space: nowrap;
                                         width: 100%;
                                         height: 100px;
                                         text-align: center;"
                            ></div>
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="count"
                        label="回复次数"
                        align="center" >
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="查看详情" placement="top-start">
                            <el-button @click="getListDetail(scope.row) "> {{scope.row.count}}</el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>


                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-edit"
                                @click="handleUpdate(scope.row)"
                        >修改</el-button>
                        <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--     分页     -->
            <el-pagination
                    v-show="total>0"
                    :page-size="queryParams.pageSize"
                    :pager-count="11"
                    :current-page.sync="queryParams.pageNum"
                    :total="total"
                    @current-change="getList"
            >
            </el-pagination>
            <!-- 添加或修改topic对话框 -->
            <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                    <el-form-item label="发布用户昵称" prop="userName">
                        <el-link>{{form.userName}}</el-link>
                    </el-form-item>
                    <el-form-item label="帖子分类" prop="classificationName">
                        <el-link>{{form.classificationName}}</el-link>
                    </el-form-item>
                    <el-form-item label="发布时间" prop="time">
                        <el-date-picker clearable size="small" style="width: 200px"
                                        v-model="form.time"
                                        type="dateTime"
                                        value-format="yyyy-MM-dd HH:mm:SS"
                                        placeholder="选择发布时间">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="帖子内容">
<!--                        <editor v-model="form.content" :min-height="192"/>-->
                        <el-input v-model="form.content" placeholder="请输入帖子内容" />
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </el-dialog>

            <!--            回复详情            -->
            <el-dialog :title="title" :visible.sync="open2" width="1000px" append-to-body  :before-close="handleClose" >
                <ComponentItem :comment="comment"/>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    // import Editor from '@/components/Editor';

    import ComponentItem from "./CommentItem.vue";

    export default {
        name: "luntan",
        // components: { Editor },
        components: {
            ComponentItem,
        },
        data() {
            return {
                //评论回复
                comment:[],
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // topic表格数据
                topicList: [],
                // 弹出层标题
                title: "",
                // 是否显示修改弹出层
                open: false,
                // 是否显示回复详情弹出层
                open2: false,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    topic:{
                        classificationId: null,
                        content: null,
                        userId: null,
                        time: null,
                        issueTime: null,
                        fatherId: null,
                        classificationName: null,
                        userName: null,
                        timeStart: null,
                        timeEnd: null
                    },
                    sidx: null,
                    sord: null,
                },
                // 发布时间
                issueTime: [],
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                },
                classificationList: [],
            };
        },
        created() {
            this.getList();
            this.getClassName();
            console.log(this.classificationList);
        },
        methods: {
            // 打开文章详情
            openHTML(introduce) {
                this.$message({
                    dangerouslyUseHTMLString: true,
                    message: introduce,
                    duration: 1000,
                });
            },
            // 查看帖子分类
            async getClassName(){
                this.loading = true;
                const token = sessionStorage.getItem("token");
                this.$http.defaults.headers.common['Authorization'] = token;
                const {data: response} = await this.$http.get('classification/list');
                this.classificationList = response.data;
                this.loading = false;
            },
            // 关闭回复详情对话框
            handleClose(done) {
                this.$confirm('确认关闭？')
                    // eslint-disable-next-line
                    .then(_ => {
                        this.getList();
                        done();
                    })
                    // eslint-disable-next-line
                    .catch(_ => {});
            },
            // 查询帖子列表
            async getList() {
                this.loading = true;
                const token = sessionStorage.getItem("token");
                this.$http.defaults.headers.common['Authorization'] = token;
                const {data: response} = await this.$http.get("topic/adminTopicList?pageNum="+this.queryParams.pageNum+'&'+"pageSize="+this.queryParams.pageSize+'&'+
                    "topic.userName="+this.queryParams.topic.userName+'&'+"topic.content="+this.queryParams.topic.content+'&'+
                    "topic.classificationName="+this.queryParams.topic.classificationName+'&'+ "topic.timeStart="+
                    this.queryParams.topic.timeStart+'&'+"topic.timeEnd="+this.queryParams.topic.timeEnd);
                this.topicList = response.data.topics;
                this.total = response.data.total;
                this.loading = false;
            },
            // 获取帖子回复详细信息
            async getListDetail(row) {
                const id = row.id;
                this.loading = true;
                const token = sessionStorage.getItem("token");
                this.$http.defaults.headers.common['Authorization'] = token;
                await this.$http.get("topic/"+id).then( response =>{
                    this.comment =  response.data.data.data;
                    this.title = "回复详情";
                    this.open2 = open;
                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.open2 = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    classificationId: null,
                    content: null,
                    userId: null,
                    time: null,
                    fatherId: null,
                    classificationName: null,
                    userName: null,
                    timeStart: null,
                    timeEnd: null
                };
                // this.$refs['form'].resetFields();
                // this.resetForm("form");
            },
            resetForm() {
                this.queryParams = {
                    pageNum: 1,
                    pageSize: 10,
                    topic:{
                        classificationId: null,
                        content: null,
                        userId: null,
                        time: null,
                        fatherId: null,
                        classificationName: null,
                        userName: null,
                        timeStart: null,
                        timeEnd: null
                    },
                },
                this.issueTime = null;
                this.handleQuery();
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                // this.resetForm("queryForm");
                this.$refs["queryForm"].resetFields();
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id)
                this.single = selection.length!==1
                this.multiple = !selection.length
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                const id = row.id || this.ids
                const token = sessionStorage.getItem("token");
                this.$http.defaults.headers.common['Authorization'] = token;
                this.$http.get('topic/'+ id).then(response => {
                    console.log(response.data.data.data);
                    this.form = response.data.data.data.topic;
                    this.open = true;
                    this.title = "修改帖子";
                });
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.id != null) {
                            const token = sessionStorage.getItem("token");
                                this.$http.defaults.headers.common['Authorization'] = token;
                                this.$http.put('topic',this.form).then(response => {
                                if (response.data.code === 200) {
                                    this.$message({showClose: true, message: "修改成功", type: "success"})
                                    this.open = false;
                                    this.getList();
                                }
                            });
                        } else {
                            const token = sessionStorage.getItem("token");
                            this.$http.defaults.headers.common['Authorization'] = token;
                            this.$http.post('topic',this.form).then(response => {
                                if (response.data.code === 200) {
                                    this.$message({ showClose: true, message: "新增成功", type: "success" })
                                    this.open = false;
                                    this.getList();
                                }
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const ids = row.id || this.ids;
                this.$confirm('是否确认删除topic编号为"' + ids + '"的数据项?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(async () => {
                    this.$http.delete(`topic/`+ids).then(response => {
                        if (response.data.code == 200) {
                            this.$message({
                                showClose: true,
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getList();
                        } else {
                            this.$message({
                                showClose: true,
                                message: response.data.msg,
                                type: response.data.code
                            });
                        }
                    });
                }).catch(() => {

                });
            },
            handleIssueTime(time) {
                this.queryParams.topic.timeStart = this.parseTime(time[0], '{y}-{m}-{d}')
                this.queryParams.topic.timeEnd = this.parseTime(time[1], '{y}-{m}-{d}')
            },
            /** 时间处理 */
            parseTime(time, pattern) {
                if (arguments.length === 0 || !time) {
                    return null
                }
                const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
                let date
                if (typeof time === 'object') {
                    date = time
                } else {
                    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
                        time = parseInt(time)
                    } else if (typeof time === 'string') {
                        time = time.replace(new RegExp(/-/gm), '/');
                    }
                    if ((typeof time === 'number') && (time.toString().length === 10)) {
                        time = time * 1000
                    }
                    date = new Date(time)
                }
                const formatObj = {
                    y: date.getFullYear(),
                    m: date.getMonth() + 1,
                    d: date.getDate(),
                    h: date.getHours(),
                    i: date.getMinutes(),
                    s: date.getSeconds(),
                    a: date.getDay()
                }
                const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
                    let value = formatObj[key]
                    // Note: getDay() returns 0 on Sunday
                    if (key === 'a') {
                        return ['日', '一', '二', '三', '四', '五', '六'][value]
                    }
                    if (result.length > 0 && value < 10) {
                        value = '0' + value
                    }
                    return value || 0
                })
                return time_str
            }
        }
    };
</script>
<style>
    .is-selected {
        color: #1989FA;
    }
    .el-card__body{
        margin-top: 10px;
    }


    .el-card{
        box-shadow: 0 1px 1px rgba(0,0,0,0.15);
    }
</style>
